package utils;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import app.Configuration;

public class ConfigReader {
	private String filename;
	private Configuration config = Configuration.getInstance();
	
	public void start() {
		
		try {		
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();
			
			DefaultHandler handler = new DefaultHandler() {
				
				boolean bdensetodiscrete = false;
				boolean bdatabasefile = false;
				
				public void startElement(String uri, String localName, String qName, Attributes attributes) {
					//System.out.println("Start element: " + qName);
					
					if (qName.equalsIgnoreCase("DenseToDiscreteStep")) {
						bdensetodiscrete = true;
					}
					
					if (qName.equalsIgnoreCase("DatabaseFile")) {
						bdatabasefile = true;
					}
				}
				
				public void endElement(String uri, String localName, String qName) {

				}
				
				public void characters(char ch[], int start, int length) {
					if (bdensetodiscrete) {
						config.setDenseToDiscreteStep(Double.parseDouble(new String(ch, start, length)));
						bdensetodiscrete = false;
					}
					
					if (bdatabasefile) {
						config.setDatabaseFile(new String(ch, start, length));
						bdatabasefile = false;
					}
				}
			};
			
			saxParser.parse(filename, handler);
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public void setFilename(String filename) {
		this.filename = filename;
	}
}
